<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="操作时间">
        <el-date-picker
          v-model="dateRange"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          :picker-options="pickerOptions"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 上方菜单栏 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['fitness:record:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-refresh"
          size="mini"
          @click="handleRedirect('calendar')"
        >日历</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-refresh"
          size="mini"
          @click="getTodayPlan('get')"
        >今日计划</el-button>
      </el-col>

      <!-- 今日计划 抽屉 -->
      <el-drawer
        title="今日计划"
        :visible.sync="drawer"
        direction="ttb"
        :with-header="false"
        size='50%'>
        <div v-for="item in planList" :key="item.basicId">
          <div style="display:flex">

            <div style="width:25%" class="upLoad-btn">
              <el-button
                type="primary"
                plain
                size="medium"
              >{{  item.basicTypeDesc }} </el-button>
            </div>

            <div style="width:25%" class="upLoad-btn">
              <el-button
                type="primary"
                plain
                size="medium"
              >{{  item.basicAmount }}    {{ item.basicUnitDesc == '次数' ? '次' : item.basicUnitDesc }}</el-button>
            </div>

            <div style="width:25%" class="upLoad-btn">
                <el-button
                  type="primary"
                  plain
                  size="medium"
                >{{   item.basicGroup  }}组</el-button>
            </div>

            <div style="width:25%" class="upLoad-btn">
              <div v-if="item.status == '2'">
                <el-button type="success" icon="el-icon-check" circle @click="updateTodayPlan(item)" ref="btnPlan"></el-button>
              </div>
              <div v-else>
                <el-button type="primary" icon="el-icon-check" circle @click="updateTodayPlan(item)" ref="btnPlan"></el-button>
              </div>
            </div>
          </div>
          <el-divider></el-divider>
        </div>
        <div style="display:flex">
          <div style="width:15%" class="upLoad-btn">
            <el-button
              type="primary"
              plain
              icon="el-icon-refresh"
              size="mini"
              @click="getTodayPlan('refresh')"
            >换一组</el-button>
          </div>
        </div>
      </el-drawer>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 折叠面板 -->
    <el-collapse accordion v-loading="loading" :data="fitnessList" @selection-change="handleSelectionChange" v-model="this.reloadPart">
      <el-collapse-item  v-for="item in fitnessList" :key="item.desc" :title="item.desc" :name="item.date">
        <div v-for="val in item.value" :key="val.type">
          <div style="display:flex">

            <div style="width:35%">
              <el-button
                type="primary"
                plain
                size="medium"
                @click="handleUpdate(val)"
                v-hasPermi="['fitness:record:edit']"
              >{{ typeDictFormatter(val.type) }}</el-button>
            </div>

            <div style="width:30%">
              <el-button
                type="primary"
                plain
                size="medium"
              >{{  val.pieces }}    {{ typeUnitDictFormatter(val.type) == '次数' ? '次' : typeUnitDictFormatter(val.type) }}</el-button>
            </div>

            <div style="width:30%">
              <div v-if="val.groupz != 0 && val.groupz != null">
                <el-button
                  type="primary"
                  plain
                  size="medium"
                >{{  val.groupz }}    组</el-button>
              </div>
            </div>

            <div style="float:right">
              <el-switch
                v-model="val.status"
                active-value="1"
                inactive-value="0"
                @change="changeSwitch(val)">
              </el-switch>
            </div>

            <template>
              <el-popconfirm
                title="确定删除该条记录吗？"
                @confirm="handleDelete(val)"
                v-hasPermi="['fitness:record:remove']"
              >
                <el-button
                  size="medium"
                  type="text"
                  icon="el-icon-delete"

                  style="float:right"
                  slot="reference"
                ></el-button>
              </el-popconfirm>
            </template>
          </div>
          <el-divider></el-divider>
        </div>
        <!-- <el-divider></el-divider> -->
      </el-collapse-item>
    </el-collapse>

    <!-- 添加或修改fitness对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="健身类型" prop="type">
          <el-cascader
          v-model="form.type"
          ref="cascaderTree"
          :options="this.treeData"
          :props="{ expandTrigger: 'hover' }"
          @change="handleTreeData()"
          ></el-cascader>
        </el-form-item>
        <el-form-item :label="unit" prop="pieces" >
          <!-- form.pieces有值(修改时)则使用原值，form.pieces没值则使用标准训练量做默认值，（改为在change方法中实现） -->
          <!-- <div v-if="(form.pieces != 1 && form.pieces != 'null') ? '' : form.pieces = this.pieces"/> -->
          <el-input-number v-model="form.pieces" controls-position="right" :min="1"/>
        </el-form-item>
        <el-form-item label="组数" prop="groupz" v-if="this.unit == '次数' || this.unit == '次'">
          <el-input-number v-model="form.groupz" controls-position="right" :min="0" />
        </el-form-item>
        <el-form-item label="日期" prop="date">
          <el-date-picker clearable
            v-model="form.date"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="完成情况" prop="status">
          <el-switch
            v-model="form.status"
            active-value="1"
            inactive-value="0">
          </el-switch>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listFitness, getFitness, delFitness, addFitness, updateFitness, updateFitnessStatus } from "@/api/fitness/record";
import { listTodayPlan, updateTodayPlan } from "@/api/fitness/plan";
import { dictBasic, treeBasic } from "@/api/fitness/basic";
export default {
  name: "Fitness",
  dicts: ['fitness_unit', 'fitness_type', 'fitness_status'],
  data() {
    return {
      //计量单位
      unit: "次数",
      //记录当前展开标签
      reloadPart: "",
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // fitness表格数据
      fitnessList: [],
      // 日期范围
      dateRange: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 标准数据记忆
      pieces: '1',
      // 今日计划抽屉
      drawer: false,
      // 今日计划集
      planList: [],
      // 树状结构
      treeData: [],
      // 字典
      placeData: [],
      typeData: [],
      unitData: [],
      typeUnitData: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        type: null,
        pieces: null,
        groupz: null,
        date: null,
        createUser: null,
        status: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        type: [
          { required: true, message: "健身类型不能为空", trigger: "change" }
        ],
        pieces: [
          { required: true, message: "次数不能为空", trigger: "blur" }
        ]
      },
      pickerOptions: {
          disabledDate: (time) => {
                let beginDate = new Date(this.startTime)
                let endDate = new Date(this.endTime)
                return time.getTime() > endDate.getTime() || time.getTime() < beginDate.getTime()
          },
          shortcuts: [
          {
            text: '昨日',
            onClick(picker) {
              const end = new Date();
              end.setTime(end.getTime() - 3600 * 1000 * 24 * 1);
              end.setHours(23);end.setMinutes(59);end.setSeconds(59);
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 1);
              start.setHours(0);start.setMinutes(0);start.setSeconds(0);
              picker.$emit('pick', [start, end]);
            }
          },
          {
            text: '今日',
            onClick(picker) {
              const end = new Date();
              end.setTime(end.getTime());
              end.setHours(end.getHours());
              end.setMinutes(end.getMinutes());
              end.setSeconds(end.getSeconds());
              const start = new Date();
              start.setTime(start.getTime());
              start.setHours(0);start.setMinutes(0);start.setSeconds(0);
              picker.$emit('pick', [start, end]);
            }
          },
          {
            text: '最近一周',
            onClick(picker) {
              const end = new Date();
              end.setHours(23);end.setMinutes(59);end.setSeconds(59);
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 6);
              start.setHours(0);start.setMinutes(0);start.setSeconds(0);
              picker.$emit('pick', [start, end]);
            }
          },
          {
            text: '最近30天',
            onClick(picker) {
              const end = new Date();
              end.setHours(23);end.setMinutes(59);end.setSeconds(59);
              const start = new Date();
              start.setHours(0);start.setMinutes(0);start.setSeconds(0);
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 29);
              picker.$emit('pick', [start, end]);
            }
          },
          {
            text: '最近90天',
            onClick(picker) {
              const end = new Date();
              end.setHours(23);end.setMinutes(59);end.setSeconds(59);
              const start = new Date();
              start.setHours(0);start.setMinutes(0);start.setSeconds(0);
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit('pick', [start, end]);
            }
          },
          {
            text: '最近一年',
            onClick(picker) {
              const end = new Date();
              end.setHours(23);end.setMinutes(59);end.setSeconds(59);
              const start = new Date();
              start.setHours(0);start.setMinutes(0);start.setSeconds(0);
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 365);
              picker.$emit('pick', [start, end]);
            }
          },
        ],
      },
    };
  },
  created() {
    this.defaultDate();
    this.getList();
  },
  methods: {
    /**   修改开关 */
    changeSwitch(data) {
      updateFitnessStatus(data).then(response =>  {
        this.reloadPart = response;
        this.getList();
      });
    },
    /** 查询fitness列表 */
    getList() {
      this.loading = true;
      dictBasic(this.queryParams).then(response => {
        this.placeData = response.place_map;
        this.typeData = response.type_map;
        this.unitData = response.unit_map;
        this.typeUnitData = response.type_unit_map;
      });
      treeBasic(this.queryParams).then(response => {
       this.treeData = response
      });
      listFitness(this.addDateRange(this.queryParams, this.dateRange)).then( response => {
        this.fitnessList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    //设置默认日期
    defaultDate(){
        //获取新的时间
        let date = new Date()
        //获取当前时间的年份转为字符串
        let year = date.getFullYear().toString()
        //获取月份，由于月份从0开始，此处要加1，判断是否小于10，如果是在字符串前面拼接'0'
        let month = date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1).toString():(date.getMonth()+1).toString()  //'04'
        //获取天，判断是否小于10，如果是在字符串前面拼接'0'
        let da = date.getDate() < 10 ? '0'+date.getDate().toString():date.getDate().toString()  //'12'
        //字符串拼接，开始时间，结束时间
        let end = year + '-' + month + '-' + da
        let beg = year + '-' + month + '-01'
        this.dateRange = [beg,end] //将值设置给插件绑定的数据
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        type: null,
        pieces: null,
        groupz: null,
        date: null,
        createTime: null,
        createUser: null,
        status: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "今日健身计划";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getFitness(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改健身计划";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateFitness(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addFitness(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
        return delFitness(ids).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('fitness/record/export', {
        ...this.queryParams
      }, `fitness_${new Date().getTime()}.xlsx`)
    },
    /** 切换为其他形式 */
    handleRedirect(route) {
      this.$router.push("/fitness/record-table/"+ route +"/")
    },
    // 类型 字典翻译
    typeDictFormatter(field) {
      return this.typeData[field];
    },
    // 计量单位 字典翻译
    typeUnitDictFormatter(field) {
      return this.typeUnitData[field];
    },
    // 状态 字典翻译
    statusDictFormatter(field, column) {
      return this.selectDictLabel(this.dict.type.fitness_status, field, "label");
    },
    // 更改健身类型，并随之更改适配的计量单位及数据量
    changeType(value) {
      var type = this.selectDictLabel(this.dict.type.fitness_type, value, "remark");
      this.pieces = this.selectDictLabel(this.dict.type.fitness_type, value, "cssClass");
      this.unit = this.selectDictLabel(this.dict.type.fitness_unit, type, "label");
      this.form.pieces = this.pieces;
    },
    // 获取今日计划
    getTodayPlan(data) {
      listTodayPlan(data).then(response =>  {
        this.planList = response.rows;
      });
      this.drawer = true;
    },
    //
    updateTodayPlan(item) {
      updateTodayPlan(item).then(response =>  {
        this.getTodayPlan();
      });
    },
    handleTreeData(){
			this.form.type = this.$refs['cascaderTree'].getCheckedNodes()[0].value;
      this.unit = this.$refs['cascaderTree'].getCheckedNodes()[0].data.unit_desc;
      this.form.pieces = this.$refs['cascaderTree'].getCheckedNodes()[0].data.amount;
      this.form.groupz = this.$refs['cascaderTree'].getCheckedNodes()[0].data.group;
		},
  }
};
</script>

<style scoped>
.upLoad-btn {
  position: relative;
  top: 50%; /*偏移*/
  transform: translateY(50%);
  text-align: center;
}

.el-button--primary {
  color: rgb(114, 26, 26);
  background-color: #e7edf3;
  border-color: #06080a;

}
.el-button--text {
  color: rgb(114, 26, 26);
}
.el-button--primary:hover {
  color: rgb(77, 11, 11);
  background-color: #7d98b3;
  border-color: #06080a;

}

.el-button--primary:focus {
  color: rgb(77, 11, 11);
  background-color: #7d98b3;
  border-color: #06080a;

}
.el-switch {
  color: rgb(77, 11, 11);
  border-color: #06080a;

}
</style>
